package com.example.cart.adapter;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.cart.CartActivity;
import com.example.cart.R;
import com.example.cart.dto.CartWithGoods;

import java.util.List;

public class CartAdapter extends BaseAdapter {
    private final Context context;
    private List<CartWithGoods> carts;
    private final View.OnClickListener deleteButtonClickedListener;

    public CartAdapter(Context cartActivity, List<CartWithGoods> carts, View.OnClickListener deleteButtonClickedListener) {

        this.context = cartActivity;
        this.carts = carts;
        this.deleteButtonClickedListener = deleteButtonClickedListener;
    }

    @Override
    public int getCount() {
        return carts.size();
    }

    @Override
    public Object getItem(int position) {
        return carts.get(position);
    }

    @Override
    public long getItemId(int position) {
        return carts.get(position).getCartId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        CartWithGoods cart = carts.get(position);
        Holder holder;
        if (convertView == null) {
            holder = new Holder();
            convertView = LayoutInflater.from(context).inflate(R.layout.cart_item, null);
            holder.goodsChecked = convertView.findViewById(R.id.goodsChecked);
            holder.goodsName = convertView.findViewById(R.id.goodsName);
            holder.goodsImage = convertView.findViewById(R.id.goodsImage);
            holder.quantity = convertView.findViewById(R.id.quantity);
            holder.removeButton = convertView.findViewById(R.id.remove);

            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }
        holder.goodsName.setText(cart.getName());
        holder.goodsImage.setImageBitmap(BitmapFactory.decodeFile(cart.getImageSrc()));
        holder.quantity.setText(String.valueOf(cart.getCartQuantity()));
        holder.removeButton.setOnClickListener(deleteButtonClickedListener);
        holder.removeButton.setTag(cart.getCartId());
        return convertView;
    }

    public void update(List<CartWithGoods> carts) {
        this.carts = carts;
        // 能通知 ListView 数据刷新
        notifyDataSetChanged();
    }


    static class Holder {
        CheckBox goodsChecked;
        TextView goodsName;
        ImageView goodsImage;
        TextView quantity;
        Button removeButton;
    }
}
